
var sticky = require('sticky-session');

sticky(function() {
    // This code will be executed only in slave workers

    var http = require('http'),
      io = require('socket.io');

    var app = require('express')();
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var app_http = http.Server(app);
    //启用bodyParser和接收post参数等
    app.use(bodyParser.json()); // for parsing application/json
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
    app.use(multer()); // for parsing multipart/form-data
    //
    var io = require('socket.io')(app_http);

    app.get('/', function(req, res){
        res.send('<h1>Welcome Realtime Server</h1>');
    });

    //首先做一个 options 的请求返回CORS的头信息。
    app.options('/push', function(req, res){
        res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
        res.setHeader('Access-Control-Allow-Credentials', true);
        res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    });

    io.on('connection', function(socket){
        console.log('a user connected');

        //监听新用户加入
        socket.on('login', function(obj){
            //将新加入用户的唯一标识当作socket的名称，后面退出的时候会用到
            socket.name = obj.userid;
            socket.unique_id = obj.userid+'-'+new Date().getTime();
            socket.join(obj.userid);//将当前的用户加入用户的房间
            //
            console.log(socket.unique_id+'加入了聊天室');
        });

        //监听用户退出
        socket.on('disconnect', function(){
            //将退出的用户从在线列表中删除
            socket.leave(socket.name);
            console.log(socket.unique_id+'退出了聊天室');
        });

    });

    //推送信息的接口
    app.get('/push', function(req, res){
        res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
        res.setHeader('Access-Control-Allow-Credentials', true);
        var uid = req.param('uid');
        var message = req.param('message');
        var action = req.param('action');
        var token = req.param('token');
        var content = {
            message : message,
            action : action
        }
        //
        if(token === "ZRa3KaxcsXCpKxRG"){
            io.to(uid).emit("message",content);
        }
        res.send('success');
    });

    return app_http;
}).listen(3000, function() {
  console.log('server started on 3000 port');
});